#include <cassert>
#include <vector>

/**
 * Keep the best (according to F_better) k elements. We maintain a "worst heap"
 * with the worst at the top. This is a based on a vector; if you change its
 * elements to violate the order, you're pretty much hosed. It would be nice
 * to use a priority_queue here, but it doesn't let us easily iterate over
 * its elements, which we want to do.
 */
template <typename T, typename F_better = std::greater<T> >
class toplist : public std::vector<T>
{
  size_t _k;
  F_better _better;
public:
  toplist(size_t k, const F_better &better = F_better())
    : _k(k), _better(better)
  {
    assert(k > 0);
  }

  /**
   * Put the item in the list, if the list has less than k elements or if it
   * has k elements but this new element is better than the worst element in
   * the list.
   */
  void insert(const T &element) {
    if (this->size() < _k || _better(element, this->front())) {
      this->push_back(element);
      std::push_heap(this->begin(), this->end(), _better);
      if (this->size() > _k) {
	std::pop_heap(this->begin(), this->end(), _better);
	this->pop_back();
      }
    }
    assert(this->size() <= _k);
  }
};
/*
* Copyright (c) 2009 John Lees-Miller
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

